package com.snowy.framework.common.base.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snowy.framework.common.constant.PageConstants;
import com.snowy.framework.util.AntiSQLFilter;
import com.snowy.framework.util.TypeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: Controller基类
 * @Author: cl
 * @Date: 2020.10.30
 * @Version: 1.0
 */
@Slf4j
public abstract  class BaseController {
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    /**
     * 获取分页对象
     *
     * @return
     */
    protected <T> Page<T> getPage() {
        return getPage(false);
    }

    /**
     * 获取分页对象
     *
     * @param openSort
     * @return
     */
    protected <T> Page<T> getPage(boolean openSort) {
        int index = 1;
        // 页数
        Integer cursor = TypeUtils.castToInt(request.getParameter(PageConstants.PAGE_PAGE), index);
        // 分页大小
        Integer limit = TypeUtils.castToInt(request.getParameter(PageConstants.PAGE_ROWS), PageConstants.DEFAULT_LIMIT);
        // 是否查询分页
        Boolean searchCount = TypeUtils.castToBoolean(request.getParameter(PageConstants.SEARCH_COUNT), true);
        limit = limit > PageConstants.MAX_LIMIT ? PageConstants.MAX_LIMIT : limit;
        Page page = new Page(cursor, limit, searchCount);
        if (openSort) {
            page.setAsc(getParameterSafeValues(PageConstants.PAGE_ASCS));
            page.setDesc(getParameterSafeValues(PageConstants.PAGE_DESCS));
        }
        return page;
    }


    /**
     * 获取安全参数(SQL ORDER BY 过滤)
     *
     * @param parameter
     * @return
     */
    protected String[] getParameterSafeValues(String parameter) {
        return AntiSQLFilter.getSafeValues(request.getParameterValues(parameter));
    }
}
